package com.cctv.portal.sms.adapter;

import com.cctv.portal.sms.adapter.ws.RespBody;
import com.cctv.portal.sms.adapter.ws.RespParser;
import com.ctvit.struts.common.CommonFunc;

import org.apache.commons.lang.StringUtils;
import org.apache.http.client.ClientProtocolException;
import org.dom4j.DocumentException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.URLEncoder;

public final class SmsAdapter {
	
	private static final String QTX_URL = CommonFunc.gatewayUrl;
	private static final String OPERA_ID = "zgcctv";
	private static final String OPERA_PASS = "zgcctv";
	
	private static final String SendTemp ="${QTX_URL}?OperID=${OperID}&OperPass=${OperPass}&" +
			"SendTime=${SendTime}&ValidTime=${ValidTime}&AppendID=${AppendID}&DesMobile=${DesMobile}&" +
			"Content=${Content}&ContentType=${ContentType}" ;
	
	private static final Logger logger = LoggerFactory.getLogger(SmsAdapter.class);
	
	public static RespBody send(String destnumbers, String msg){
		return send(destnumbers, msg, "");
	}
	
	public static RespBody send(String destnumbers, String msg, String extCode){
		RespBody respBody = new RespBody();
		String uri = SendTemp.replace("${QTX_URL}", QTX_URL);
		uri = uri.replace("${OperID}", OPERA_ID);
		uri = uri.replace("${OperPass}", OPERA_PASS);
		uri = uri.replace("${ContentType}", "8");
		uri = uri.replace("${SendTime}", "");
		uri = uri.replace("${ValidTime}", "");
		uri = uri.replace("${AppendID}", extCode);
		uri = uri.replace("${DesMobile}", destnumbers);
//		msg = msg+"【中央电视台】";
		try {
			uri = uri.replace("${Content}", URLEncoder.encode(msg, "GBK"));
			String result =HttpClientUtil.executeRequest(uri);
			if(StringUtils.isNotEmpty(result)){
				respBody = RespParser.parseXml(result);
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
			logger.error(e.getMessage(), e.getCause());
		} catch (IOException e) {
			e.printStackTrace();
			logger.error(e.getMessage(), e.getCause());
		} catch (DocumentException e) {
			e.printStackTrace();
			logger.error(e.getMessage(), e.getCause());
		}
		return respBody;
	}
}
